import { merge } from 'lodash'
import {loginByUsername, getUserInfo} from '@/api/login'
// eslint-disable-next-line camelcase
import { setToken, getToken, removeToken } from '../../utils/token'

const state = {
  id: '',
  status: '',
  username: '',
  role: 'guest',
  token: getToken()
}

const mutations = {
  SET_USER_INFO (state, userInfo) {
    merge(state, userInfo)
  },
  SET_TOKEN (state, token) {
    state.token = token
  },
  LOGOUT (state) {
    state.id = ''
    state.username = ''
    state.status = ''
    state.role = 'guest'
    state.token = ''
  }
}

const actions = {
  // init user info
  // initUserInfo ({ commit, dispatch, state }) {
  //   return new Promise((resolve, reject) => {
  //     // token
  //     if (username) {
  //       getUserInfo(state.access_token).then(data => { // eslint-disable-line
  //         if (data._id) {
  //           commit('SET_USER_INFO', data)
  //         }
  //         resolve(data)
  //       }).catch(err => { reject(err) })
  //     } else {
  //       resolve()
  //     }
  //   })
  // },
  login ({ commit }, userInfo) {
    return new Promise((resolve, reject) => {
      loginByUsername(userInfo.username, userInfo.password).then(response => {
        const data = response.data
        commit('SET_TOKEN', data.token)
        setToken(data.token)
        resolve()
      }).catch(err => { reject(err) })
    })
  },
  userInfo ({commit}) {
    return new Promise((resolve, reject) => {
      getUserInfo().then(response => {
        const data = response.data
        commit('SET_USER_INFO', data)
        resolve()
      }).catch(err => { reject(err) })
    })
  },
  // refresh token action
  refreToken ({ commit }, payload) {
    commit('REFERE_TOKEN', payload)
  },
  // logout action
  logout ({ commit }, payload) {
    commit('LOGOUT')
    removeToken()
  }
}

const getters = {
  id (state) {
    return state.id
  },
  role (state) {
    return state.role
  },
  username (state) {
    return state.username
  }
}

export default {
  state,
  mutations,
  actions,
  getters
}
